#include "client.h"
#include "QDebug"
#include "QHostAddress"
#include <QNetworkProxy>

Client::Client(QObject *parent) : QTcpSocket(parent)
{
    //    m_tcp = new QTcpSocket(parent);
    Server_port = 7890;
    connect(this, &QTcpSocket::readyRead, this, &Client::ReadyReadData_cb);
    connect(this, &QTcpSocket::connected, this, &Client::Connect_cb);       // 连接客户端断开信号
    connect(this, &QTcpSocket::disconnected, this, &Client::Disconnect_cb); // 连接客户端断开信号
    this->setProxy(QNetworkProxy::NoProxy);                                 // 禁用代理服务器
}
void Client::Set_server_info(QString ip)
{
    Server_ip = ip;
}
uint8_t Client::Connect_server(void)
{
    //    m_tcp->connectToHost(server_ip, server_port, QTcpSocket::ReadWrite);

    qDebug() << "host_ip:" << Server_ip << "port:" << Server_port << endl;
    // 连接服务器
    this->connectToHost(Server_ip, Server_port);
    if (waitForConnected(3000))
    {
        qDebug() << "连接成功";
        return 0;
    }
    else
    {
        qDebug() << "连接失败：" << this->errorString();
        return 1;
    }
    /*连接检查定时器*/
}

void Client::SendData(QByteArray data)
{
    // 数据做base64转码
    //    QByteArray base64 = data.toUtf8().toBase64();
    //    QString le;
    //    // 预留8字节保存长度
    //    le.sprintf("%08d", base64.size());
    //    // 拼接数据 报文长度+报文
    //    base64 = le.toUtf8() + base64;
    // 发送数据
    if (state() == QTcpSocket::ConnectedState)
    {
        this->write(data);
    }
}

void Client::Disconnect_cb(void)
{
    emit DisconnectedSignal(NULL);
    //    qDebug()<<"disconnect_cb";
}
void Client::Connect_cb(void)
{
    emit ConnectedSignal(NULL);
    //    qDebug()<<"connect_cb";
}

void Client::ReadyReadData_cb()
{
    // 拿到发送信号的客户端指针，通过该指针读取数据
    emit RecvSignal(this->readAll());
}
